<template>
    <div class="chat-area">
      <el-scrollbar class="chat-messages" ref="scrollbar">
        <div v-if="chatMessages.length === 0" class="chat-msg_zero">
          <div class="zero_card">
            <div class="zero_left">
              <h1>{{ t("chat.chatSubtitle") }}</h1>
              <p>{{ t("chat.chatPlaceholder") }}</p>
              <p>{{ t("chat.chatExample") }}</p>
            </div>
            <div class="zero_right">
              <img src="../../assets/images/机器人数量icon.png" />
            </div>
          </div>
        </div>
        <div
          v-for="(message, index) in chatMessages"
          :key="index"
          :class="[ 'chat-message', message.sender === 'assistant' ? 'ai' : 'user' ]"
        >
          <div class="message-container">
            <img class="message-avatar" :src="messageAvatar(message.sender)" />
            <div class="message-content">{{ message.content }}</div>
            <!-- 添加闪动光标 -->
            <div v-if="message.sender === 'assistant'" class="cursor-blink">|</div>
          </div>
        </div>
      </el-scrollbar>
  
      <div class="chat-input-area">
        <input
          class="inputarea"
          v-model="inputValue"
          placeholder="Enter 发送"
          @keydown.enter.prevent="handleSendMessage"
        />
        <div class="input-area-buttom">
          <el-button class="input-buttons-send" @click="handleSendMessage">
            {{ t("chat.chatSendButton") }}
          </el-button>
        </div>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, nextTick, reactive } from "vue";
  import { t } from "../../locales"; // 引入全局 i18n
  
  const chatMessages = ref<{ sender: string; content: string }[]>([]);
  const inputValue = ref("");
  const scrollbar = ref<any>(null); // 用于引用 el-scrollbar
  
  // 根据发送者返回头像
  const messageAvatar = (sender: string) => {
    return sender === "assistant" ? "/ai-avatar.png" : "/user-avatar.png";
  };
  
  // 调用 AI API 的函数
  const callAiApi = async (userMessage: string) => {
    const apiKey = "bce-v3/ALTAK-mpmEA0UbCHXFOUohK8jju/207e2c82611d0ed260e8878d28d00fcdd99bb0b9";
    const base_url = "https://qianfan.baidubce.com/v2/chat/completions";
  
    if (!userMessage.trim()) return;  // 如果消息为空，则直接返回
  
    // 构造历史对话
    const messages = chatMessages.value.map(msg => ({
      role: msg.sender === "user" ? "user" : "assistant", // 使用 user 或 assistant 角色
      content: msg.content
    }));
  
    // 添加当前用户消息
    messages.push({ role: "user", content: userMessage });
  
    const body = {
      model: "ernie-3.5-8k",
      messages: messages,
      stream: true,  // 开启流式返回
      stream_options: {
        include_usage: false  // 是否包含 token 使用信息，默认为 false
      }
    };
  
    console.log('API 请求体:', JSON.stringify(body));  // 打印请求体
  
    try {
      const resp = await fetch(base_url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization':`Bearer ${apiKey}`,
        },
        body: JSON.stringify(body),
      });
  
      // 检查响应是否成功
      if (!resp.ok) {
        const errorText = await resp.text();
        console.error(`AI 请求失败: ${resp.status} ${resp.statusText}`, errorText);
        return;
      }
  
      // 预先添加空的AI消息对象（使用reactive确保响应式）
      const aiMessage = reactive({ sender: "assistant", content: "" });
      chatMessages.value.push(aiMessage);
      scrollToBottom(); // 立即滚动到底部
    //@ts-ignore
      const reader = resp.body.getReader();
      const decoder = new TextDecoder();
      let buffer = '';
      let done = false;
  
      while (!done) {
        const { value, done: readerDone } = await reader.read();
        done = readerDone;
        buffer += decoder.decode(value || new Uint8Array(), { stream: !done });
  
        // 按行分割处理流数据
        let lineIndex;
        while ((lineIndex = buffer.indexOf('\n')) !== -1) {
          const line = buffer.slice(0, lineIndex).trim();
          buffer = buffer.slice(lineIndex + 1);
  
          if (line.startsWith('data: ')) {
            const jsonStr = line.slice(6).trim();
            if (jsonStr === '[DONE]') continue;
  
            try {
              const data = JSON.parse(jsonStr);
              const deltaContent = data.choices[0]?.delta?.content || '';
              if (deltaContent) {
                aiMessage.content += deltaContent; // 逐步更新内容
                scrollToBottom(); // 每次更新后滚动
              }
            } catch (error) {
              console.error('解析JSON失败:', error);
            }
          }
        }
      }
    } catch (error) {
      console.error("AI 请求失败:", error);
    }
  };
  
  // 滚动到底部
  const scrollToBottom = () => {
    nextTick(() => {
      if (scrollbar.value) {
        scrollbar.value.scrollTo(0, scrollbar.value.scrollHeight); // 使用 scrollTo 来控制滚动
      }
    });
  };
  
  // 发送消息处理
  const handleSendMessage = () => {
    const message = inputValue.value.trim();
    if (!message) return; // 如果输入为空，则不发送请求
    console.log("发送的消息:", message);
  

  
    // 清空输入框
    inputValue.value = "";
  
    // 调用 AI API 获取回复
    callAiApi(message);
  };
  </script>
  
  <style scoped lang="scss">
  .chat-area {
    padding: 20px;
    display: flex;
    box-sizing: border-box;
    flex-direction: column;
    width: 100%;
    height: 100%;
    background-color: rgb(255, 255, 255);
    box-shadow: 2px 0 2px 0 rgba(0, 0, 0, 5%);
    border-radius: 0 32px 32px 0;
    overflow-x: hidden;
  
    .chat-messages {
      flex-grow: 1;
      padding: 10px;
      box-sizing: border-box;
  
      .chat-msg_zero {
        width: 100%;
        display: flex;
        justify-content: center;
  
        .zero_card {
          display: flex !important;
          align-items: center;
          justify-content: space-between;
          width: 50%;
          background-color: rgb(249, 249, 249);
  
          border-radius: 2rem;
          padding: 2rem;
  
          .zero_left {
            display: inline-block;
  
            h1 {
              font-weight: 700;
              font-size: 1.5rem;
              margin-bottom: 1rem;
            }
  
            p {
              font-size: 1.2rem;
              color: #777;
              margin-bottom: 1rem;
            }
          }
  
          .zero_right {
            display: inline-block;
          }
        }
      }
  
      /* 用户消息样式 */
      .chat-message.user .message-content {
        font-size: 18px;
        background-color: #e9e6e6;
        /* 白底 */
        color: #000000;
        /* 黑字 */
        font-family: "Arial", sans-serif;
        /* 修改字体样式 */
      }
  
      .chat-message.ai .message-content {
        font-size: 18px;
        background-color: rgb(106, 132, 244);
        /* 蓝底 */
        color: rgb(245, 242, 242);
        /* 白字 */
        font-family: "Arial", sans-serif;
        /* 修改字体样式 */
      }
  
      /* 头像样式 */
      .message-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        margin-right: 10px;
        margin-bottom: 5px;
      }
  
      /* 消息容器样式 */
      .message-container {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
      }
  
      .chat-message.user .message-container {
        align-items: flex-end;
      }
  
      .chat-message.ai .message-container {
        align-items: flex-start;
      }
  
      .message-content {
        display: inline-block;
        padding: 10px 15px;
        border-radius: 10px;
        max-width: 70%;
        /* 限制消息宽度，不超过容器的 70% */
        word-wrap: break-word;
        /* 长单词自动换行 */
        word-break: break-all;
        /* 如果一行太长则强制换行 */
        overflow-wrap: break-word;
        /* 确保文本换行 */
      }
  
      /* 闪动光标样式 */
      .cursor-blink {
        animation: blink 3s infinite;
        font-size: 18px;
        color: #fff;
        font-weight: 700;
      }
  
      @keyframes blink {
        0%{
          opacity: 0;
        }
        50% {
          opacity: 1;
        }
        100%{
          opacity: 0;
        }
      }
    }
  
    .chat-input-area {
      display: flex;
      flex-direction: column;
      border: 2px solid skyblue;
      padding: 10px;
      margin: 5px;
      background-color: #fff;
      border-radius: 20px;
      box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.1);
      margin-top: 10px;
  
      .inputarea {
        border: none;
        outline: none;
        /* 去掉焦点时的轮廓 */
        height: 40px;
        /* 设置高度为两行 */
        line-height: 20px;
        /* 每行的高度 */
        font-size: 16px;
        /* 设置字体大小 */
      }
  
      .input-buttons-send {
        margin-left: 10px;
        padding: 8px 12px;
        background-color: rgb(26, 161, 239);
        color: white;
        border: none;
        border-radius: 12px;
        cursor: pointer;
        width: 4rem;
        height: 2rem;
      }
  
      .input-area-buttom {
        display: flex;
        justify-content: end;
      }
    }
  }
  </style>